define(function(require) {
    'use strict';

    var Marionette = require('marionette');

    return Marionette.CollectionView.extend({

        className: 'app-fields',

        initialize: function(options) {
            this.options = options || {};
            this.layout = this.options.layout;
        },

        onShow: function() {
            this.sortable();
        },

        itemViewOptions: function() {
            return {
                layout: this.layout
            };
        },

        // override Marionette.CollectionView.addItemView
        addItemView: function(item) {
            if(item.get('type') === 'config') return;
            return Marionette.CollectionView.prototype.addItemView.apply(this, arguments);
        },

        // override Marionette.CollectionView.getItemView
        getItemView: function(item) {
            var type = item.get('type');
            return window.SHOWCASE_CONFIG.showViews[type];
        },

        sortable: function() {
            var view = this;

            this.$el.sortable({
                // 只允许在垂直方向拖动
                axis: 'y',
                items: '> div:not(.js-not-sortable)',
                cursor: 'move',
                start: function(event, ui) {
                    ui.item.data('startPos', ui.item.index());
                },
                stop: function(event, ui) {
                    var startPos = ui.item.data('startPos'),
                        endPos = ui.item.index();

                    if(startPos === endPos) return;

                    if(view.includeConfigModel()){
                        startPos = startPos + 1;
                        endPos = endPos + 1;
                    }

                    view.sort(startPos, endPos, view.collection.models);
                    view.layout.displayEditView();
                    view.collection.trigger('sort');
                }
            });
        },

        sort: function(startPos, endPos, arr){
            // 删除元素
            var item = arr.splice(startPos, 1)[0];
            // 插入元素
            arr.splice(endPos, 0, item);
            return arr;
        },

        includeConfigModel: function(){
            return this.collection.includeConfigModel();
        },

        // override Marionette.CollectionView.isEmpty
        isEmpty: function() {
            // check if we're empty now
            return !this.collection || (this.includeConfigModel() && this.collection.length === 1) || this.collection.length === 0;
        }
    });
});
